#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>

#include "auxiliaire.h"
#include "types.h"

/*____________________________________________________________________________*/

/*!
 * \brief Retourne un numéro de page et un mode d'accès
 *
 * @param[in] page_max Maximum de pages TODO faire la description
 * @param[out] *type Type d'accès (Lecture ou Ecriture)
 *
 * @return Le numéro de la page
 */
static int get_page(int page_max, acces *type) {

    if(aleat(0,1)) *type = Lecture;
    else *type = Ecriture;

    return aleat(0,page_max-1);
}

/*____________________________________________________________________________*/

static void init_surv(fd_set *s, struct timeval *t) {
    FD_ZERO(s);
    FD_SET(fileno(stdin), s);
    t-> tv_sec = 0;
    t-> tv_usec = 300;
    return;
}

/*____________________________________________________________________________*/

int main(int argc, char * argv []) {
    fd_set wt;
    struct timeval timeout;

    int page_num;
    acces type_acces;
    int page_max;

    s_processus state;
    s_processus retval;

    char buffer[BUFFER_SIZE];

    state = InStop;

    if (argc != 2) {
        fprintf(stderr, "[proc]%s <max_page >\n", argv [0]);
        exit(EXIT_FAILURE);
    }

    page_max = atoi(argv [1]);
    if (page_max <= 1) {
        page_max = 2;
    }

    state = InStop;

    init_surv(&wt, &timeout);
    while (1) {

        select(fileno(stdin) + 1, &wt, NULL, NULL, &timeout);
        retval = state;
        if (FD_ISSET(fileno(stdin), &wt) && !feof(stdin)) {
        	s_processus s;

            if( read_and_parse(stdin,buffer,NULL,NULL)<=0 )
            	fprintf(stderr,"[proc]<< Demande invalide >>\n");
            else{
            	s = str2s_processus(buffer);
            	if(s==INERROR)
            		fprintf(stderr,"[proc]<< Demande invalide >>\n");
            	else
            		retval = s;
            }

        }

        switch(retval){
			case InRun:
				page_num = get_page(page_max, &type_acces);
				fprintf( stdout, "%c%d\n", (type_acces == Ecriture ? 'W' : 'R'),
						 page_num);
				fflush(stdout);
				break;

			case InKill_proc:
				exit(EXIT_SUCCESS);

			default:
				break;
        }
        state = retval;
        init_surv(&wt, &timeout);
    }
    exit(EXIT_FAILURE);
}

/*____________________________________________________________________________*/
